<script lang="ts" setup>
// @ts-ignore
import QRCode from "qrcodejs2-fix";
import * as MiniProgramApi from "@/api/mini-program/index";
import { useUserStore } from "@/store/modules/user";
import html2canvas from "html2canvas";
import { showToast } from "@nutui/nutui";
import * as PosterApi from "@/api/system/poster/index";

type PosterType = "mall" | "course";

const props = defineProps<{
  type: PosterType;
}>();

const userStore = useUserStore();
// 用户信息
const userInfo = useUserStore().userInfo;
const saleInfo = ref<UserInfo | null>(userInfo);

const posterImg = ref(""); // 大海报展示
const posterCacheMap = new Map<number, string>(); // 海报缓存
const posterList = ref<PosterApi.Poster[]>([]);

const currentBgIndex = ref(0);

const getPosterList = () => {
  const posterType = props.type === "mall" ? "0" : "1";
  PosterApi.pagePoster({ pageNo: 1, pageSize: 10, posterType }).then(async (res) => {
    posterList.value = await res.data.list.filter((item:PosterApi.Poster)=>{
      return item.ifSwitch === 1
    });
    posterList.value.length && createH5Qrcode(props.type, userStore.auth.userId);
  });
};


// 背景图片加载状态
const bgImgLoaded = ref(false);
const handleBgChange = (index: number) => {
  currentBgIndex.value = index;
  bgImgLoaded.value = false;
};
const handleBgImgLoad = () => {
  bgImgLoaded.value = true;
};

// 二维码图片加载状态
const qrCodeImgLoaded = ref(false);

const qrCodeWrapper = ref<HTMLDivElement>();
let qrCodeMaker: QRCode | null = null;

// 创建h5二维码
const createH5Qrcode = (type: PosterType, userId: string) => {
  qrCodeMaker && (qrCodeMaker._el.innerHTML = "");
  qrCodeMaker = null;
  qrCodeMaker = new QRCode(qrCodeWrapper.value, {
    width: posterList.value[currentBgIndex.value].qrCodeWidth * 16,
    height: posterList.value[currentBgIndex.value].qrCodeHeight * 16,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: (QRCode as any).CorrectLevel.H,
  }) as any;

  qrCodeImgLoaded.value = true;

  const baseURL = window.location.origin;
  const path = {
    mall: "mall",
    course: "course",
  }[type];
  const url = `${baseURL}/h5/#/${path}?uid=${userId}`;
  qrCodeMaker?.clear();
  qrCodeMaker?.makeCode(url);
};

// 创建小程序二维码
const createMiniProgramQrcode = async (type: PosterType, userId: string) => {
  const path = {
    mall: "/mall",
    course: "course",
  }[type];

  const scene = `${path}?uid=${userId}`;

  const res = await MiniProgramApi.createQrCode({
    scene,
    page: "pages/index/index",
    width: 430,
    checkPath: false,
    autoColor: false,
    lineColor: { r: "87", g: "172", b: "229" },
    isHyaline: true,
  });

  const blob = new Blob([res], { type: "image/jpeg" });
  const imageUrl = URL.createObjectURL(blob);
  const imgEl = new Image();
  // 设置宽高
  imgEl.style.width = "100%";
  imgEl.style.height = "100%";
  imgEl.onload = () => {
    qrCodeWrapper.value?.appendChild(imgEl);
    qrCodeImgLoaded.value = true;
  };
  imgEl.src = imageUrl;
};

const posterEl = ref<HTMLDivElement>();
const mounted = ref(false);
watchEffect(() => {
  // 击中缓存
  if (posterCacheMap.has(currentBgIndex.value)) {
    posterImg.value = posterCacheMap.get(currentBgIndex.value)!;
    showToast.hide();
    return;
  }

  // 新的生成
  if (bgImgLoaded.value && qrCodeImgLoaded.value) {
    createH5Qrcode(props.type, userStore.auth.userId);
    // 生成海报
    html2canvas(posterEl.value!, {
      width: posterEl.value!.offsetWidth,
      height: posterEl.value!.offsetHeight,
      //按比例增加分辨率
      scale: window.devicePixelRatio, // 设备像素比
      useCORS: true, //（图片跨域相关）
      allowTaint: true, //允许跨域（图片跨域相关）
      logging: false,
      // @ts-ignore
      letterRendering: true,
    }).then((canvas) => {
      const base64 = canvas.toDataURL("image/png");
      posterCacheMap.set(currentBgIndex.value, base64);
      posterImg.value = base64;
      showToast.hide();
    });
  } else if (posterList.value.length) {
    mounted.value &&
      showToast.loading("加载中...", {
        duration: 0,
      });
  }
});

onMounted(async () => {
  mounted.value = true;
  showToast.loading("正在加载海报...");
  // isMiniProgram() ? createMiniProgramQrcode(props.type, userStore.auth.userId) : createH5Qrcode(props.type, userStore.auth.userId);
  getPosterList();
});
</script>

<template>
  <div class="h-screen bg-gray-1 flex flex-col">
    <!-- 标题栏 -->
    <div class="shrink-0 flex-center h-12 bg-white shadow-sm">海报推广</div>

    <!-- 海报元素，用一个不限大小的div，放在看不见的地方 -->
    <div class="fixed -z-1">
      <!-- 这个是海报元素 -->
      <div ref="posterEl" class="relative">
        <img :src="posterList[currentBgIndex]?.posterUrl" alt="" @load="handleBgImgLoad" />
        <div
          class="absolute z-20 bg-white"
          :style="`right:${posterList[currentBgIndex]?.qrCodePositionRight}rem;bottom:${
            posterList[currentBgIndex]?.qrCodePositionBottom
          }rem;padding:${posterList[currentBgIndex]?.qrCodeWidth * 0.05}rem`"
        >
          <div
            :style="`width:${posterList[currentBgIndex]?.qrCodeWidth}rem;height:${posterList[currentBgIndex]?.qrCodeHeight}rem;`"
            ref="qrCodeWrapper"
          ></div>
          <div
            class="absolute p-0.5 bg-white rounded"
            :style="`width:${posterList[currentBgIndex]?.qrCodeWidth * 0.4}rem;height:${posterList[currentBgIndex]?.qrCodeHeight * 0.4}rem;right:${
              posterList[currentBgIndex]?.qrCodeHeight * 0.35
            }rem;top:${posterList[currentBgIndex]?.qrCodeHeight * 0.35}rem`"
          >
            <img class="w-full h-full rounded" :src="saleInfo?.avatar" alt="" />
          </div>
        </div>
      </div>
    </div>

    <!-- 海报 -->
    <div v-if="posterImg" class="grow of-y-auto py-5">
      <img class="w-3/4 h-auto mx-auto" :src="posterImg" alt="" />
    </div>

    <!-- 空状态 -->
    <div v-else class="grow of-y-auto py-5">
      <nut-empty description="暂无海报"></nut-empty>
    </div>

    <!-- 候选图片 -->
    <div class="p-3 rounded-t-xl bg-white shadow-lg">
      <p class="pb-2 text-center c-gray-5">选择一个背景，然后长按上方海报即可保存</p>
      <div class="scroll overflow-x-auto whitespace-nowrap h-28 overflow-hidden">
        <div
          v-if="posterList"
          v-for="(item, index) in posterList"
          :key="index"
          class="w-18 h-full inline-block align-top mr-4 border-5 rounded-xl overflow-hidden"
          :class="[currentBgIndex == index ? 'border-blue-300' : 'border-transparent']"
          @click="handleBgChange(index)"
        >
          <nut-image :src="item.posterUrl" fit="cover" lazy-load class="w-full h-full rounded-xl"></nut-image>
          <img :src="item.posterUrl" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>
